
<template>

  <el-card class="backCol">
    <el-row >
      <el-col :span="20">
        <el-form :inline="true" size="mini" ref="clientRefForm" :model="clientQuery" class="demo-form-inline">
          <el-form-item label="关键字">
            <el-input v-model="clientQuery.keyword" placeholder="请输入用户名/昵称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  @click="handleQuery">查 询</el-button>
            <el-button type="primary"   @click="onReset">重 置</el-button>
            <el-button type="primary" @click="addClient">添加客户</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
  <el-table
      stripe :data="clientList"
      style="width: 100%"
      @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="编号"/>
    <el-table-column prop="avatar" label="头像">
      <template v-slot="scope">
        <el-avatar :src="scope.row.avatar || defaultImgUrl"/>
      </template>
    </el-table-column>
    <el-table-column prop="username" label="用户名"/>
    <el-table-column prop="nickname" label="昵称"/>
    <el-table-column prop="gender" label="性别">
      <template v-slot="scope">
        <div class="detail">&nbsp
          {{scope.row.gender ===1 ?'男':'女'}}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="signature" :show-overflow-tooltip="true" label="个性签名"/>
    <el-table-column prop="status" label="账号状态">
      <template v-slot="scope">
        <el-switch
            active-value="0"
            inactive-value="1"
            v-model="scope.row.status"
            @click="handleStatusChange(scope.row)">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column prop="ctime" label="账号创建时间"/>
    <el-table-column prop="utime" label="账号更新时间"/>


    <el-table-column label="操作" width="230px">
      <template #default="scope" >
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger"  @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @prev-click="toPage"
      @next-click="toPage"
      @current-change="toPage"/>
  <!--新增用户的对话框弹窗-->
  <el-dialog v-model="clientDialogVisible" :title="clientQuery.id>0 ?'编辑用户':'新增用户'" width="55%" center draggable>
    <el-form  ref="clientRefForm" :model="clientQuery" label-width="auto" style="max-width: 600px" :rules="clientRules">
      <el-input type="hidden" v-show="false" v-model="clientQuery.id"/>
      <el-form-item label="用户名" prop="username">
        <el-input  v-model="clientQuery.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input  v-model="clientQuery.nickname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="clientQuery.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="个性签名" prop="signature">
        <el-input type="textarea" :rows="2" v-model="clientQuery.signature"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="clientDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="clientSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {getToken, messageConfirm, messageTip} from "../util/Util.js";
import axios from "axios";

export default {
  name: "ClientView",
  //注入父级页面提供provide的所有属性（函数，属性，对象）
  data(){
    return{
      //用户列表数据
      clientList : [{}],
      pageSize : 0,
      total : 0,
      //用户的弹窗是否弹出来，true就弹出来，false就不弹出来
      clientDialogVisible :false,
      //定义用户表单对象, 初始值是空
      clientQuery:{
        keyword:null
      },
      //定义用户验证规则-数组对象
      clientRules:{
          username:[{required:true,message:'用户名不能为空',trigger: 'blur'}],
      },
      //用户id的数组
      clientIdArray:[],
      defaultImgUrl:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      options : [
        {label : '男', value : 0},
        {label : '女', value : 1}
      ]
    }
  },

  mounted() {
    this.getData(1);
  },

  methods:{


    //跟据关键字进行查询
    handleQuery() {
      //搜索
        this.getData(1);
    },


    //重置搜索框
    onReset() {
      this.clientQuery.keyword=null;
      this.$router.go(0);
    },
    //勾选或者取消勾选时，触发该函数
    handleSelectionChange(selectionDataArray){
      console.log(selectionDataArray);
      selectionDataArray.forEach(data=>{
        let clientId=data.id;
        this.clientIdArray.push(clientId);
      })
    },
    //查询用户列表数据方法
    getData(current){
      let keyword=this.clientQuery.keyword
      doGet("/api/clients",{
        current : current,//当前查询第几页
        keyword: keyword
      }).then(resp=>{
        console.log(resp)
        if(resp.data.code===200){
          this.clientList=resp.data.data.list;
          this.pageSize=resp.data.data.pageSize;
          this.total=resp.data.data.total;
        }
      })
    },
    //分页函数(current这个形参是element-plus组件自动传过来的，就是传的当前页)
    toPage(current){
      this.getData(current)
    },
    //点击新增用户按钮时，触发该函数
    addClient(){
      this.clientQuery={};
      this.clientDialogVisible=true;//弹出对话框
    },
    //新增和编辑客户，提交保存
    clientSubmit(){
      let formData=new FormData();
      //把新增的每个字段数据追加到formData里面
      for(let field in this.clientQuery){
        formData.append(field,this.clientQuery[field]);//字段名和字段值K-V
      }
      this.$refs.clientRefForm.validate((isValid)=>{
        if(isValid){
          if(this.clientQuery.id>0){//编辑
            doPut("/api/client",formData).then(resp=>{
              if(resp.data.code===200){
                messageTip("编辑成功","success");
                this.$router.go(0);
              }else{
                messageTip("编辑失败","error");
              }
            })
          }else {//新增
            doPost("/api/client",formData).then(resp=>{
              if(resp.data.code===200){
                messageTip("新增成功","success");
                //页面刷新
                this.clientDialogVisible=false;//关闭对话框
              }else{
                messageTip("新增失败","error");
                this.clientDialogVisible=false;//关闭对话框
              }
            })
          }
        }
      })
    },
    //编辑用户
    edit(id){
      this.clientDialogVisible=true;
      this.loadClient(id);
    },
    //加载用户信息
    loadClient(id) {
      doGet("/api/client/" + id, {}).then(resp => {
        if (resp.data.code === 200) {
          this.clientQuery = resp.data.data;
        }
      })
    },
    //删除单个用户
    //删除
    del (id) {
      messageConfirm("您确定要删除该数据吗？").then(() => { //用户点击“确定”按钮就会触发then函数
        doDelete("/api/client/" + id, {}).then(resp => {
          console.log(resp);
          if (resp.data.code === 200) {
            messageTip("删除成功", "success");
            this.$router.go(0);
          } else {
            messageTip("删除失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => { //用户点击“取消”按钮就会触发catch函数
        messageTip("取消删除", "error");
      })
    },
    handleStatusChange(row){
      let statusTip =row.status ==='0'?'启用':'禁用'
      messageConfirm(`是否确认[${statusTip}]该客户?`).then(() => { //用户点击“确定”按钮就会触发then函数
        doPut("/api/client/changeStatus",{
          id : row.id,
          status: row.status
        }).then(resp => {
          console.log(resp);
          if (resp.data.code === 200) {
            messageTip("修改成功", "success");
            setTimeout(() => {
            }, 1000); // 延迟 1 秒（与消息提示的显示时长匹配）
          } else {
            messageTip("修改失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => { //用户点击“取消”按钮就会触发catch函数
        //将当前用户的状态值还原到设置前状态
        messageTip("取消修改", "error");
        row.status=row.status===0?1:0
      })
    },
    //导出客户的Excel数据
    exportExcel(ids) {
      let token = getToken();
      //1，向后端发送一个请求(后端返回文件流)
      let iframe = document.createElement("iframe");
      if(ids) {
        //说明是选择导出
        iframe.src=axios.defaults.baseURL+"/api/exportExcel?Authorization="+token+"&ids="+ids;
      }else {
        //对应httpRequest.js文件（后端接口地址的前缀）
        iframe.src = axios.defaults.baseURL+"/api/exportExcel?Authorization="+token;
      }
      //通过样式隐藏在浏览器页面的iframe框(让其在页面上不要显示出来)
      iframe.style.display="none";
      //在document树结构里面添加该元素
      document.body.appendChild(iframe);
      //2，后端在查询数据库的数据时，把数据写入excel中，然后把excel以IO流的方式
      //输出到前端浏览器

      //3，前端浏览器弹出一个下载框进行文件下载（浏览器本身会实现）
    }
  }
}

</script>

<style scoped>

</style>

